﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Composition;
using System.Configuration.Install;
using System.Linq;
using System.IO;
using System.Reflection;
using System.ServiceProcess;
using Toolbox.Plugin;
using System.Collections.ObjectModel;

namespace Toolbox
{
    public partial class Service : ServiceBase
    {

        [ImportMany]
        [Browsable(false)]
        [ReadOnly(true)]
        public IPluginThread[] Threads { get; private set; }

        public Service()
        {
            this.InitializeComponent();

            PluginItem[] items = PluginItem.FromPluginList(this.Threads.Cast<IPlugin>()).ToArray();


            foreach (PluginItem t in items)
            {
                t.Plugin.BeginInit();
            }

            foreach (PluginItem t in items)
            {
                t.Configure();
            }

            foreach (PluginItem t in items)
            {
                t.Plugin.EndInit();

            }

        }

        protected override void OnContinue()
        {
            foreach (PluginThread t in this.Threads.Distinct<IPluginThread>())
            {
                if (t.IsRunning)
                {
                    t.Start();
                }
            }
        }

        protected override void OnPause()
        {
            foreach (PluginThread t in this.Threads.Distinct<IPluginThread>())
            {
                if (t.IsRunning)
                {
                    t.Pause();
                }
            }
        }

        protected override void OnStart(string[] args)
        {
            foreach (PluginThread t in this.Threads.Distinct<IPluginThread>())
            {
                if (!t.IsRunning)
                {
                    t.Start();
                }
            }
        }

        protected override void OnStop()
        {
            foreach (PluginThread t in this.Threads.Distinct<IPluginThread>())
            {
                if (t.IsRunning)
                {
                    t.Stop();
                }
            }
        }

        internal void Start(string[] args)
        {
            this.OnStart(args);
        }
    }
}


